package logic

import (
	"context"
	"fmt"
	"math/rand"
	"strconv"
	"wechat/model/mysql"
	"wechat/model/redisinit"

	"wechat/userrpc/internal/svc"
	"wechat/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserAddLogic {
	return &UserAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserAddLogic) UserAdd(in *userrpc.UserAddRequest) (*userrpc.UserAddResponse, error) {
	// todo: add your logic here and delete this line

	var findtuser mysql.User
	mysql.DB.Where("tel = ?", in.Tel).Find(&findtuser)
	if findtuser.ID != 0 {
		return nil, fmt.Errorf("该手机号已经被注册，请更换其他手机号")
	}
	get := redisinit.Rdb.Get("sendsms" + in.Tel + "useradd")
	if in.Smscode != get.Val() {
		return nil, fmt.Errorf("短信验证码输入错误，请重试")
	}

	wxnum := rand.Intn(9000000) + 1000000

	user := mysql.User{
		UserName: "wx" + strconv.Itoa(wxnum),
		Address:  in.Address,
		Tel:      in.Tel,
		Password: in.Password,
	}
	err := mysql.DB.Create(&user).Error
	if err != nil {
		return nil, fmt.Errorf("注册失败")
	}

	return &userrpc.UserAddResponse{
		Id: int64(findtuser.ID),
	}, nil
}
